package com.knowledge.controller;


import com.knowledge.common.aop.TokenValidate;
import com.knowledge.common.constant.GlobalConstant;
import com.knowledge.common.enums.ErrorCode;
import com.knowledge.dao.entity.NewsEntity;
import com.knowledge.dao.entity.SysUser;
import com.knowledge.service.NewsService;
import com.knowledge.utils.UserThreadLocal;
import com.knowledge.vo.Result;
import com.knowledge.vo.params.NewsParam;
import com.knowledge.vo.params.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p>
 * 消息表 前端控制器
 * </p>
 *
 * @author zzz
 * @since 2022-03-03
 */
@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @TokenValidate
    @PostMapping("/list")
    public Result list(@RequestBody NewsParam newsParam){
        //分页参数
        PageParams pageParams = new PageParams();
        pageParams.setPage(newsParam.getPage());
        pageParams.setPageSize(newsParam.getPageSize());
        //设置用户
        newsParam.setUserId(UserThreadLocal.get().getId());
        /*if (newsParam.getIsRead() == null){
            newsParam.setIsRead(GlobalConstant.NO);
        }*/
        return newsService.listNewsWithPage(newsParam, pageParams);
    }

    @TokenValidate
    @PostMapping("/read")
    public Result read(@RequestBody Map<String, Object> params){
        if (params.get("newsId") == null){
            return Result.fail(ErrorCode.PARAMS_ERROR);
        }
        //当前用户
        SysUser sysUser = UserThreadLocal.get();
        //消息ID
        Integer newsId = Integer.parseInt(params.get("newsId").toString());
        NewsEntity newsEntity = newsService.getById(newsId);
        if (newsEntity.getUserId().equals(sysUser.getId())){
            newsService.updateToRead(newsId);
            return Result.success();
        }else {
            return Result.fail(ErrorCode.NEWS_READ_ID_ERROR);
        }
    }
}
